package com.zhuzi.batch.config;

import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.connection.JmsTransactionManager;
import org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter;
import org.springframework.jms.core.JmsOperations;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @author zhuzi
 * 2023/12/21 17:22
 */
//@Configuration
public class IbmMqConfig {
    @Value("${ibmmq.host}")
    private String host;

    @Value("${ibmmq.port}")
    private Integer port;

    @Value("${ibmmq.username}")
    private String username;

    @Value("${ibmmq.password}")
    private String password;

    @Value("${ibmmq.channel}")
    private String channel;

    @Value("${ibmmq.manager}")
    private String manager;

    @Value("${ibmmq.ccsid}")
    private Integer ccsid;

    @Value("${ibmmq.receive-timeout}")
    private Long receiveTimeout;

    @Value("${ibmmq.concurrency}")
    private String concurrency;

    /**
     * 配置连接工厂:
     * CCSID要与连接到的队列管理器一致，Windows下默认为1381，
     * Linux下默认为1208。1208表示UTF-8字符集，建议把队列管理器的CCSID改为1208
     *
     * @return
     */
    @Bean("mqQueueConnectionFactory")
    public MQQueueConnectionFactory mqQueueConnectionFactory() {
        MQQueueConnectionFactory mqQueueConnectionFactory = new MQQueueConnectionFactory();
        mqQueueConnectionFactory.setHostName(host);
        try {
            mqQueueConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
            mqQueueConnectionFactory.setCCSID(ccsid);
            mqQueueConnectionFactory.setChannel(channel);
            mqQueueConnectionFactory.setPort(port);
            mqQueueConnectionFactory.setQueueManager(manager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqQueueConnectionFactory;
    }

    /**
     * 配置连接认证:
     * 如不需要账户密码链接可以跳过此步，直接将mqQueueConnectionFactory注入下一步的缓存连接工厂。
     *
     * @param mqQueueConnectionFactory
     * @return
     */
//    @Bean("userCredentialsConnectionFactoryAdapter")
    UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter(MQQueueConnectionFactory mqQueueConnectionFactory) {
        UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
        userCredentialsConnectionFactoryAdapter.setUsername(username);
        userCredentialsConnectionFactoryAdapter.setPassword(password);
        userCredentialsConnectionFactoryAdapter.setTargetConnectionFactory(mqQueueConnectionFactory);
        return userCredentialsConnectionFactoryAdapter;
    }

    /**
     * 配置缓存连接工厂:
     * 不配置该类则每次与MQ交互都需要重新创建连接，大幅降低速度。
     */
    @Bean("cachingConnectionFactory")
    public CachingConnectionFactory cachingConnectionFactory(MQQueueConnectionFactory mqQueueConnectionFactory) {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setTargetConnectionFactory(mqQueueConnectionFactory);
        cachingConnectionFactory.setSessionCacheSize(500);
        cachingConnectionFactory.setReconnectOnException(true);
        return cachingConnectionFactory;
    }

    /**
     * 配置事务管理器:
     * 不使用事务可以跳过该步骤。
     * 如需使用事务，可添加注解@EnableTransactionManagement到程序入口类中，
     * 事务的具体用法可参考Spring Trasaction。
     * 需要注意：这里配置的事务会影响到@Service层的数据库事务，故暂时不使用
     *
     * @param cachingConnectionFactory
     * @return
     */
//    @Bean("jmsTransactionManager")
    public PlatformTransactionManager jmsTransactionManager(CachingConnectionFactory cachingConnectionFactory) {
        JmsTransactionManager jmsTransactionManager = new JmsTransactionManager();
        jmsTransactionManager.setConnectionFactory(cachingConnectionFactory);
        return jmsTransactionManager;
    }

    /**
     * 配置JMS模板:
     * 重要：不设置setReceiveTimeout时，
     * 当队列为空，从队列中取出消息的方法将会一直挂起直到队列内有消息
     *
     * @param cachingConnectionFactory
     * @return
     */
    @Bean("jmsOperations")
    public JmsOperations jmsOperations(CachingConnectionFactory cachingConnectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(cachingConnectionFactory);
        return jmsTemplate;
    }

    /**
     * 配置DefaultJmsListenerContainerFactory,
     * 用@JmsListener注解来监听队列消息时候，尤其存在多个监听的时候，
     * 通过实例化配置DefaultJmsListenerContainerFactory来控制消息分发
     *
     * @param cachingConnectionFactory
     * @return
     */
    @Bean(name = "jmsListenerContainerFactory")
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(CachingConnectionFactory cachingConnectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory);
        //设置连接数，如果对消息消费有顺序要求，这里建议设置为"1-1"
        factory.setConcurrency(concurrency);
        //重连间隔时间
        factory.setRecoveryInterval(receiveTimeout);
        return factory;
    }
}
